<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col :span="2" class="addUser">
          <el-button type="primary" @click="">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="rolePermList" stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i==0 ? 'bdtop' : '','ventor' ]" v-for="(item,i) in scope.row.children" :key="item.id">
              <!--一级菜单-->
              <el-col :span="5">
                <el-tag closable @close="rmPermById(scope.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[j==0 ? '' : 'bdtop','ventor']" v-for="(item1,j) in item.children" :key="item1.id">
                  <el-col :span="6">
                    <el-tag type="success" @close="rmPermById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" @close="rmPermById(scope.row,item2.id)" closable v-for="item2 in item1.children"
                      :key="item2.id">{{item2.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号">
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showAlloaDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="分配权限" :visible.sync="alloaPermDialogVisible" @close="clearDefkeys" width="50%">
      <el-tree :data="permTree" show-checkbox
               default-expand-all node-key="id"
               ref="refTree" highlight-current
               :props="permTreeProps"
               :default-checked-keys="defKeys"
      >
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="alloaPermDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allocaPerm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        rolePermList: [],
        alloaPermDialogVisible: false,
        permTree: [],
        permTreeProps: {
          children: 'children',
          label: 'authName'
        },
        defKeys: [],
		roleId:''
      }
    },
    methods: {
      async getAllRolePerm() {
        let {
          data: res
        } = await this.$http.get('/role/roles/tree');
        if (res.meta.status !== 200) return this.$message.error('角色权限获取失败');
        this.rolePermList = res.data;
      },
      async rmPermById(role, pid) {
        if (role.id == 0) {
          return this.$message.error('没有操作权限')
        }
        let resultConfirm = await this.$confirm(
          '此操作将永久删除该权限, 是否继续?',
          '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).catch(error => error)
        if (resultConfirm !== 'confirm') {
          return this.$message.info('操作已取消')
        }
        let {
          data: res
        } = await this.$http.get(`/role/roles/${role.id}/perm/${pid}`);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        role.children = res.data;
      },
      async showAlloaDialog(role) {
		  this.roleId= role.id;
        let {
          data: res
        } = await this.$http.get('/role/rights/tree');
        if (res.meta.status !== 200) return this.$message.error('权限列表获取失败');
        this.permTree = res.data;
        this.getDefKeys(role,this.defKeys)
        this.alloaPermDialogVisible = true;
      },
      // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
      getDefKeys(node, arr) {
        // 如果当前 node 节点不包含 children 属性，则是三级节点
        if (!node.children) {
          return arr.push(node.id)
        }
        node.children.forEach(item => {
          this.getDefKeys(item, arr);
        })
      },
      clearDefkeys() {
        this.defKeys = [];
      },
	 async allocaPerm(  ){
		  //获取全选和半选的权限id
			let keys = [
				this.$refs.refTree.getCheckedKeys(),
				this.$refs.refTree.getHalfCheckedKeys()
			]
				let idArr = keys.join(',');
				let{data:res} = await this.$http.post(`/role/roles/${this.roleId}`,{
					psids:idArr
				})
				if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
				this.$message.success(res.meta.msg)
				this.getAllRolePerm()
				this.alloaPermDialogVisible = false
	  }
    },
    created() {
      this.getAllRolePerm();
    }
  }
</script>

<style lang="scss">
.el-tag{
  margin: 7px;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.bdtop{
  border-top: 1px solid #eee;
}
.ventor{
  display: flex;
  align-items: center;
}
</style>
